<template>
  <div style="margin-left: 14%">
    <!-- 试品类型配置页 -->
    <el-breadcrumb separator="/">
      <!--面包屑 -->
      <el-breadcrumb-item>
        <i class="el-icon-s-home" style="margin-right: 15px; font-size: 16px"></i>试品类型配置
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="info">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item class="roleInput" label="试品类型">
              <el-input v-model.trim="formInline.productKind" placeholder="请输入试品类型" clearable  size="small"></el-input>
            </el-form-item>
            <el-form-item class="search" label="">
              <el-button size="small" @click="search" style="float: right;" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-row>
          <el-button class="addBtn global_add" @click="addProduct" :disabled="btnList.add" style="float:right; margin-right: 15px;margin-bottom: 5px;" type="text">+&nbsp;新增试品类型</el-button>
        </el-row>
        <el-table border stripe :data="productKindList" style="width: 100%">
          <el-table-column align="center" prop="pk_ch_name" label="试品类型名称">
          </el-table-column>
          <el-table-column align="center" prop="pk_en_name" label="试品类型英文名称">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button class="global_edit" type="text" @click="editProduct(scope.row)" size="small" :disabled="btnList.edit">编辑</el-button>
              <el-button class="global_delete" type="text" @click="deleteProduct(scope.row)" style="color: red" size="small" :disabled="btnList.delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div v-show="flag" class="block">
            <el-pagination background @current-change="currentChange" :current-page="currentPage"
                layout="prev, pager, next"
                :total="count">
            </el-pagination>
        </div>
      </el-card>
    </div>
    <!-- 新增弹出框 -->
    <el-dialog
        title="新增试品类型"
        :visible.sync="dialogVisible"
        width="450px">
        <el-form label-position="right" :rules="rules" ref="form" :model="form" label-width="120px"  size="small">
            <el-form-item class="mb" label="试品类型" prop="name">
                <el-input type="textarea" v-model.trim="form.name" autosize placeholder="请输入试品类型名称" style="width: 90%" clearable></el-input>
            </el-form-item>
            <el-form-item label="试品类型英文" prop="en_name">
                <el-input type="textarea" v-model.trim="form.en_name" autosize placeholder="请输入试品类型英文名称" style="width: 90%" clearable></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button class="textBtn" @click="cancel"  size="small">取 消</el-button>
            <el-button  type="primary" @click="define"  size="small">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog
        title="编辑试品类型"
        :visible.sync="editdialogVisible"
        width="450px">
        <el-form label-position="right" :rules="rules" ref="editForm" :model="form" label-width="120px"  size="small">
            <el-form-item class="mb" label="试品类型" prop="name">
                <el-input type="textarea" v-model.trim="form.name" placeholder="请输入试品类型名称" autosize style="width: 90%" clearable></el-input>
            </el-form-item>
            <el-form-item label="试品类型英文" prop="en_name">
                <el-input type="textarea" v-model.trim="form.en_name" placeholder="请输入试品类型英文名称" autosize style="width: 90%" clearable></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button class="textBtn" @click="editCancel"  size="small">取 消</el-button>
            <el-button type="primary" @click="editDefine"  size="small">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import roleBtn from '../../public/means'
import Bus from '../../public/eventBus'
export default {
    data() {
      var validateName = (rule, value, callback) => {
        let reg = /^[\u4e00-\u9fa5]{0,}$/
        if(!reg.test(value)){
            callback(new Error('类型名称只能为汉字！'));
        }
        callback();
      }
      var validateEnName = (rule, value, callback) => {
        let reg = /^[A-Za-z0-9-_.,"'\[\]{\|}！￥……*;:~!@#$%^&()（）、——+=?？，。；：’“”‘\\/\s]{0,}$/
        if(!reg.test(value)){
            callback(new Error('类型英文名称不运行输入汉字！'));
        }
        callback();
      }
    return {
      formInline: {
        productKind: "",
      },
      productKindList: [
      ],
      menu_id: 23,
      count:0,
      uuid:'',
      currentPage: 1,
      roleBtnArr: [],
      flag: true,
      btnList: {
        add: false,
        edit: false,
        delete: false
      },
      dialogVisible: false,
      editdialogVisible: false,
      form: {
          name:'',
          en_name: ''
      },
      rules: {
          name: [
            { required: true, message: '请输入试品类型名称', trigger: 'blur' },
            // { validator: validateName, trigger: 'blur' }
          ],
          en_name: [
            { required: true, message: '请输入试品类型英文名称', trigger: 'blur' },
            { validator: validateEnName, trigger: 'blur' }
          ]
      }
    }
  },
  async created() {
      this.keyupSubmit()
      const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      this.getProductKindList()
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  },
  mounted() {
    Bus.$emit('setHeight')
    Bus.$emit('getHeight')
  },
  methods: {
      keyupSubmit(){
        document.onkeydown=e=>{
          let _key=window.event.keyCode;
          if(_key===13){
            this.search()
          }
        }
      },
      async getProductKindList() {
          const { result,count } = await this.$http.get('/getProductKindList')
          this.productKindList = result.splice(0, 10)
          this.count = count
      },
      editProduct(row) {
          this.editdialogVisible = true
          this.form.name = row.pk_ch_name
          this.form.en_name = row.pk_en_name
          this.uuid = row.pk_id
      },
      async deleteProduct(row) {
          const confirm = await this.$confirm('此操作将永久删除该试品类型, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(confirm !== 'confirm') {
            return this.$message('已取消删除！')
        }
          const res = await this.$http.delete(`/deletebyIdProductKind?pk_id=${row.pk_id}`)
          if(res.code !== 200) {
              return this.$message(res.message)
          }
          this.count--;
          const { result } = await this.$http.get('/getProductKindList')
          if(this.currentPage !== 1){
            this.productKindList = result.splice((this.currentPage-1)*10, 10)
            if(this.productKindList.length === 0) {
                this.currentPage--
                this.currentChange(this.currentPage)
            }
          }else{
            this.productKindList = result.splice(0, 10)
          }
          this.$message.success(res.message)
      },
      async currentChange(val) {
          this.currentPage = val
          const { result } = await this.$http.get('/getProductKindList')
          if(val !== 1){
            this.productKindList = result.splice((val-1)*10, 10)
          }else{
            this.productKindList = result.splice(0, 10)
          } 
      },
      addProduct(){
          this.dialogVisible = true
      },
      cancel() {
          this.dialogVisible = false
          this.$refs.form.resetFields()
      },
      editCancel() {
          this.editdialogVisible = false
          this.$refs.editForm.resetFields()
          this.form.name = '',
          this.form.en_name = ''
      },
      async editDefine() {
          const flag = await this.$refs.editForm.validate().catch(err=>err)
          if(!flag) {
              return
          }
          const res = await this.$http.post('putNameProductKind',{pk_id: this.uuid, pk_ch_name: this.form.name, pk_en_name: this.form.en_name})
          if(res.code !== 200) {
              return this.$message(res.message)
          }else{
            this.$message.success(res.message)
            this.productKindList.forEach(item => {
                if(item.pk_id === this.uuid) {
                    item.pk_ch_name = this.form.name
                    item.pk_en_name = this.form.en_name
                }
            })
          }
          this.form.name = ''
          this.form.en_name = ''
          console.log(this.uuid);
          this.editdialogVisible = false
      },
      async define() {
          const flag = await this.$refs.form.validate().catch(err=>err)
          if(!flag) {
              return
          }
        //   console.log('新增元件');
        const res = await this.$http.post('/addProductKind',{pk_ch_name: this.form.name, pk_en_name: this.form.en_name}).catch(err=>err)
        if(res.code !== 200) {
            return
        }else{
          this.form.name = ''
          this.form.en_name = ''
            this.count++;
            this.productKindList.splice(-1,1)
            this.productKindList.unshift(res.result)
            this.$message.success(res.message)
        }
        this.dialogVisible = false
      },
      async search() {
        if(this.formInline.productKind){
          const { result } = await this.$http.post('/byNameProductKind',{pk_name: this.formInline.productKind})
          this.productKindList = result
          this.flag = false
        }else{
          this.flag = true
          this.currentChange(this.currentPage)
        }
      }
  }

}
</script>

<style lang="scss" scoped>
@import "./ProductUnitLib.scss";
</style>